//
//  ContactPickerViewController.m
//  Guazi
//
//  Created by koolearn on 11-5-20.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ContactPickerViewController.h"
#import "User.h"
#import "ProfileImageCell.h"
#import "ImageStore.h"
#import "GuaziAppDelegate.h"


@implementation ContactPickerViewController


@synthesize searchBar;
@synthesize searchDC;
@synthesize filtedUsers;
@synthesize users;
@synthesize delegate;
@synthesize action;


#pragma mark -
#pragma mark Initialization


- (id) initWithDelegate:(id)aDelegate action:(SEL)act
{
    self = [super init];
	if ( self ) {
		self.delegate = aDelegate;
		self.action = act;
	}
	return self;
}


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"选择联系人";
	
	self.users = [User loadAllUsers];

	// Create a search bar
	self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)] autorelease];
	self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
	self.searchBar.keyboardType = UIKeyboardTypeAlphabet;
	self.tableView.tableHeaderView = self.searchBar;
	
	// Create the search display controller
	self.searchDC = [[[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self] autorelease];
	self.searchDC.searchResultsDataSource = self;
	self.searchDC.searchResultsDelegate = self;
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	if ( self.tableView == tableView ) {
		return [users count];
	}
	else {
		// Search table
		NSPredicate *predicate = [NSPredicate predicateWithFormat:@"screenName contains[cd] %@", self.searchBar.text];
		self.filtedUsers = [users filteredArrayUsingPredicate:predicate];
		return [filtedUsers count];
	}
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    User* user = nil;
	if ( self.tableView == tableView ) {
		user = [users objectAtIndex:indexPath.row];
	}
	else {
		user = [filtedUsers objectAtIndex:indexPath.row];
	}

    static NSString *CellIdentifier = @"ContactPickerViewCell";
    
    ProfileImageCell *cell = (ProfileImageCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[ProfileImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
	cell.textLabel.text = user.screenName;
	
	NSString* photo = user.profileImageUrl_s;
	if ( photo && [photo length]>0 ) {
		cell.imageView.image = [cell getProfileImage:photo isLarge:NO];
	}
	else {
		cell.imageView.image = [ImageStore defaultProfileImage:NO];
	}
	
    return cell;
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    User* user = nil;
	if ( self.tableView == tableView ) {
		user = [users objectAtIndex:indexPath.row];
	}
	else {
		user = [filtedUsers objectAtIndex:indexPath.row];
	}

	if ( delegate && action ) {
		[delegate performSelector:action withObject:user];
		[self.navigationController popViewControllerAnimated:YES];
	}
}


#pragma mark - section index

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)aTableView 
{
    NSMutableDictionary* dic = [NSMutableDictionary dictionary];
    
    NSArray* userArray = nil;
    if ( self.tableView == aTableView ) {
        userArray = users;
    }
    else {
        userArray = filterUsers;
    }
    
    for ( User* user in userArray ) {
        NSString* py = user.pyLetters;
        if ( !py || [py length] == 0 ) continue;
        NSString* s = [py substringToIndex:1];
        if ( [dic objectForKey:s] == nil ) {
            [dic setObject:s forKey:s];
        }
    }
    
    NSArray* sortedArray = [[dic allValues] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    return sortedArray;
}


- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSArray* userArray = nil;
    if ( self.tableView == tableView ) {
        userArray = users;
    }
    else {
        userArray = filterUsers;
    }
    
    NSInteger row = -1;
    for ( int i=0; i<[userArray count]; i++ ) {
        User* user = [userArray objectAtIndex:i];
        NSString* py = user.pyLetters;
        if ( !py || [py length]==0 ) continue;
        
        
        if ( [title compare:py]!=NSOrderedDescending ) {
            row = i;
            break;
        }
    }
    
    if ( index >= 0 ) {
        [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
	return -1;
}



#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
	self.searchBar = nil;
	self.searchDC = nil;
	self.users = nil;
	self.filtedUsers = nil;
	self.delegate = nil;
}


- (void)dealloc {
	[searchBar release];
	[searchDC release];
	[users release];
	[filtedUsers release];
	[delegate release];
    [super dealloc];
}


@end

